<template>
  <div class="strategy">
    <h2>量化策略</h2>
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else>
      <el-tabs v-model="activeTab" class="strategy-tabs">
        <el-tab-pane label="移动平均线策略" name="ma"></el-tab-pane>
        <el-tab-pane label="RSI策略" name="rsi"></el-tab-pane>
        <el-tab-pane label="布林带策略" name="bb"></el-tab-pane>
        <el-tab-pane label="海龟交易策略" name="turtle"></el-tab-pane>
        <el-tab-pane label="多因子选股策略" name="multiFactor"></el-tab-pane>
      </el-tabs>
      
      <div class="strategy-content">
        <!-- 移动平均线策略 -->
        <div v-if="activeTab === 'ma'" class="strategy-form">
          <h3>移动平均线策略</h3>
          <el-form @submit.prevent="executeMAStrategy" label-width="120px">
            <el-form-item label="股票代码:">
              <el-input 
                v-model="maStrategy.symbol" 
                placeholder="请输入股票代码"
                style="width: 300px;"
              />
            </el-form-item>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="短期周期:">
                  <el-input-number 
                    v-model="maStrategy.shortPeriod" 
                    :min="1"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="长期周期:">
                  <el-input-number 
                    v-model="maStrategy.longPeriod" 
                    :min="1"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-button type="primary" @click="executeMAStrategy" :loading="executing">
              {{ executing ? '执行中...' : '执行策略' }}
            </el-button>
          </el-form>
        </div>
        
        <!-- RSI策略 -->
        <div v-if="activeTab === 'rsi'" class="strategy-form">
          <h3>RSI策略</h3>
          <el-form @submit.prevent="executeRSIStrategy" label-width="120px">
            <el-form-item label="股票代码:">
              <el-input 
                v-model="rsiStrategy.symbol" 
                placeholder="请输入股票代码"
                style="width: 300px;"
              />
            </el-form-item>
            
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="周期:">
                  <el-input-number 
                    v-model="rsiStrategy.period" 
                    :min="1"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
              
              <el-col :span="8">
                <el-form-item label="超买阈值:">
                  <el-input-number 
                    v-model="rsiStrategy.overbought" 
                    :min="50"
                    :max="100"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
              
              <el-col :span="8">
                <el-form-item label="超卖阈值:">
                  <el-input-number 
                    v-model="rsiStrategy.oversold" 
                    :min="0"
                    :max="50"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-button type="primary" @click="executeRSIStrategy" :loading="executing">
              {{ executing ? '执行中...' : '执行策略' }}
            </el-button>
          </el-form>
        </div>
        
        <!-- 布林带策略 -->
        <div v-if="activeTab === 'bb'" class="strategy-form">
          <h3>布林带策略</h3>
          <el-form @submit.prevent="executeBBStrategy" label-width="120px">
            <el-form-item label="股票代码:">
              <el-input 
                v-model="bbStrategy.symbol" 
                placeholder="请输入股票代码"
                style="width: 300px;"
              />
            </el-form-item>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="周期:">
                  <el-input-number 
                    v-model="bbStrategy.period" 
                    :min="1"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="倍数:">
                  <el-input-number 
                    v-model="bbStrategy.multiplier" 
                    :step="0.1"
                    :min="0.1"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-button type="primary" @click="executeBBStrategy" :loading="executing">
              {{ executing ? '执行中...' : '执行策略' }}
            </el-button>
          </el-form>
        </div>
        
        <!-- 海龟交易策略 -->
        <div v-if="activeTab === 'turtle'" class="strategy-form">
          <h3>海龟交易策略</h3>
          <el-form @submit.prevent="executeTurtleStrategy" label-width="120px">
            <el-form-item label="股票代码:">
              <el-input 
                v-model="turtleStrategy.symbol" 
                placeholder="请输入股票代码"
                style="width: 300px;"
              />
            </el-form-item>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="入市周期:">
                  <el-input-number 
                    v-model="turtleStrategy.entryPeriod" 
                    :min="1"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="出市周期:">
                  <el-input-number 
                    v-model="turtleStrategy.exitPeriod" 
                    :min="1"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-button type="primary" @click="executeTurtleStrategy" :loading="executing">
              {{ executing ? '执行中...' : '执行策略' }}
            </el-button>
          </el-form>
        </div>
        
        <!-- 多因子选股策略 -->
        <div v-if="activeTab === 'multiFactor'" class="strategy-form">
          <h3>多因子选股策略</h3>
          <el-form @submit.prevent="executeMultiFactorStrategy" label-width="200px">
            <el-form-item label="股票池:">
              <el-input 
                v-model="multiFactorStrategy.symbols" 
                type="textarea"
                placeholder="请输入股票代码，如：000001,600000,000858"
                :rows="3"
                style="width: 500px;"
              />
            </el-form-item>
            
            <el-form-item label="因子权重配置:">
              <div class="factor-weight">
                <el-row :gutter="20">
                  <el-col :span="12" v-for="(weight, factor) in multiFactorStrategy.factorWeights" :key="factor">
                    <el-form-item :label="`${factorMap[factor]} (${factor}):`">
                      <el-slider 
                        v-model="multiFactorStrategy.factorWeights[factor]" 
                        :min="-1"
                        :max="1"
                        :step="0.1"
                        show-input
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-form-item>
            
            <el-form-item label="选股数量:">
              <el-input-number 
                v-model="multiFactorStrategy.topN" 
                :min="1"
                :max="50"
                controls-position="right"
              />
            </el-form-item>
            
            <el-button type="primary" @click="executeMultiFactorStrategy" :loading="executing">
              {{ executing ? '执行中...' : '执行策略' }}
            </el-button>
          </el-form>
        </div>
      </div>
      
      <!-- 策略执行结果 -->
      <div v-if="strategyResult" class="strategy-result">
        <h3>策略执行结果</h3>
        <div class="result-content">
          <div class="result-summary">
            <div class="result-item">
              <span class="result-label">建议操作:</span>
              <span class="result-value" :class="getActionClass(strategyResult.signal)">
                {{ getActionText(strategyResult.signal) }}
              </span>
            </div>
            <div class="result-item">
              <span class="result-label">理由:</span>
              <span class="result-value">{{ getReasonText(strategyResult) }}</span>
            </div>
          </div>
          <div class="result-details">
            <h4>详细信息:</h4>
            <pre>{{ JSON.stringify(strategyResult, null, 2) }}</pre>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import apiService from '../services/ApiService';

const activeTab = ref('ma');
const executing = ref(false);
const error = ref(null);
const strategyResult = ref(null);

// 监听activeTab变化，清空结果数据
watch(activeTab, (newTab, oldTab) => {
  if (newTab !== oldTab) {
    strategyResult.value = null;
    error.value = null;
  }
});

const maStrategy = ref({
  symbol: '',
  shortPeriod: 5,
  longPeriod: 20
});

const rsiStrategy = ref({
  symbol: '',
  period: 14,
  overbought: 70,
  oversold: 30
});

const bbStrategy = ref({
  symbol: '',
  period: 20,
  multiplier: 2
});

const turtleStrategy = ref({
  symbol: '',
  entryPeriod: 20,
  exitPeriod: 10
});

const multiFactorStrategy = ref({
  symbols: '',
  factorWeights: {
    momentum: 0.3,
    volatility: -0.2,
    volume: 0.2,
    price: 0.3
  },
  topN: 10
});

const factorMap = {
  momentum: '动量因子',
  volatility: '波动性因子',
  volume: '成交量因子',
  price: '价格因子'
};

const executeMAStrategy = async () => {
  try {
    executing.value = true;
    error.value = null;
    strategyResult.value = null;
    
    const response = await apiService.executeMovingAverageStrategy(maStrategy.value);
    
    // 修复：检查响应中是否有error属性来判断是否出错
    if (!response || response.error) {
      error.value = response?.error || '策略执行失败';
    } else {
      strategyResult.value = response.data;
    }
  } catch (err) {
    error.value = '网络错误，请稍后重试';
    console.error('移动平均线策略执行失败:', err);
  } finally {
    executing.value = false;
  }
};

const executeRSIStrategy = async () => {
  try {
    executing.value = true;
    error.value = null;
    strategyResult.value = null;
    
    const response = await apiService.executeRSIStrategy(rsiStrategy.value);
    
    // 修复：检查响应中是否有error属性来判断是否出错
    if (!response || response.error) {
      error.value = response?.error || '策略执行失败';
    } else {
      strategyResult.value = response.data;
    }
  } catch (err) {
    error.value = '网络错误，请稍后重试';
    console.error('RSI策略执行失败:', err);
  } finally {
    executing.value = false;
  }
};

const executeBBStrategy = async () => {
  try {
    executing.value = true;
    error.value = null;
    strategyResult.value = null;
    
    const response = await apiService.executeBollingerBandsStrategy(bbStrategy.value);
    
    // 修复：检查响应中是否有error属性来判断是否出错
    if (!response || response.error) {
      error.value = response?.error || '策略执行失败';
    } else {
      strategyResult.value = response.data;
    }
  } catch (err) {
    error.value = '网络错误，请稍后重试';
    console.error('布林带策略执行失败:', err);
  } finally {
    executing.value = false;
  }
};

const executeTurtleStrategy = async () => {
  try {
    executing.value = true;
    error.value = null;
    strategyResult.value = null;
    
    const response = await apiService.executeTurtleTradingStrategy(turtleStrategy.value);
    
    // 修复：检查响应中是否有error属性来判断是否出错
    if (!response || response.error) {
      error.value = response?.error || '策略执行失败';
    } else {
      strategyResult.value = response.data;
    }
  } catch (err) {
    error.value = '网络错误，请稍后重试';
    console.error('海龟交易策略执行失败:', err);
  } finally {
    executing.value = false;
  }
};

const executeMultiFactorStrategy = async () => {
  try {
    executing.value = true;
    error.value = null;
    strategyResult.value = null;
    
    // 处理股票代码输入
    const symbols = multiFactorStrategy.value.symbols
      .split(',')
      .map(s => s.trim())
      .filter(s => s.length > 0);
    
    if (symbols.length === 0) {
      error.value = '请至少输入一个股票代码';
      return;
    }
    
    const requestData = {
      symbols: symbols,
      factorWeights: multiFactorStrategy.value.factorWeights,
      topN: multiFactorStrategy.value.topN
    };
    
    const response = await apiService.executeMultiFactorStrategy(requestData);
    
    // 修复：检查响应中是否有error属性来判断是否出错
    if (!response || response.error) {
      error.value = response?.error || '策略执行失败';
    } else {
      strategyResult.value = response.data;
    }
  } catch (err) {
    error.value = '网络错误，请稍后重试';
    console.error('多因子策略执行失败:', err);
  } finally {
    executing.value = false;
  }
};

// 辅助函数：更新因子权重
const updateFactorWeight = (factor, value) => {
  multiFactorStrategy.value.factorWeights[factor] = parseFloat(value) || 0;
};

// 辅助函数：将信号转换为操作文本
const getActionText = (signal) => {
  switch (signal) {
    case 'BUY':
      return '买入';
    case 'SELL':
      return '卖出';
    case 'HOLD':
    default:
      return '持有';
  }
};

// 辅助函数：获取操作的CSS类
const getActionClass = (signal) => {
  switch (signal) {
    case 'BUY':
      return 'action-buy';
    case 'SELL':
      return 'action-sell';
    case 'HOLD':
    default:
      return 'action-hold';
  }
};

// 辅助函数：生成理由文本
const getReasonText = (result) => {
  if (result.signal === 'BUY') {
    if (result.hasOwnProperty('entryUpper')) {
      // 海龟交易策略
      return `价格突破入市通道上轨(${result.entryUpper.toFixed(2)})，建议买入`;
    } else if (result.hasOwnProperty('rsi')) {
      // RSI策略
      return `RSI值(${result.rsi.toFixed(2)})低于超卖阈值(${result.oversold})，建议买入`;
    } else if (result.hasOwnProperty('upperBand')) {
      // 布林带策略
      return `价格触及布林带下轨(${result.lowerBand.toFixed(2)})，建议买入`;
    } else {
      // 移动平均线策略
      return `短期均线上穿长期均线，建议买入`;
    }
  } else if (result.signal === 'SELL') {
    if (result.hasOwnProperty('entryLower')) {
      // 海龟交易策略
      return `价格突破入市通道下轨(${result.entryLower.toFixed(2)})，建议卖出`;
    } else if (result.hasOwnProperty('rsi')) {
      // RSI策略
      return `RSI值(${result.rsi.toFixed(2)})高于超买阈值(${result.overbought})，建议卖出`;
    } else if (result.hasOwnProperty('upperBand')) {
      // 布林带策略
      return `价格触及布林带上轨(${result.upperBand.toFixed(2)})，建议卖出`;
    } else {
      // 移动平均线策略
      return `短期均线下穿长期均线，建议卖出`;
    }
  } else {
    // 多因子策略
    if (result.hasOwnProperty('score')) {
      return `综合得分为 ${result.score.toFixed(2)}，在股票池中排名前 ${result.rank || 'N'} 位`;
    }
    return '根据策略分析，建议继续持有';
  }
};
</script>

<style scoped>
.strategy {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.loading, .error {
  text-align: center;
  padding: 20px;
}

.error {
  color: #dc3545;
  background-color: #f8d7da;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
  margin: 20px 0;
}

.strategy-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.strategy-tabs button {
  padding: 12px 24px;
  background-color: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
}

.strategy-tabs button.active,
.strategy-tabs button:hover {
  background-color: #007bff;
  color: white;
  border-color: #007bff;
}

.strategy-form {
  background-color: #f8f9fa;
  padding: 25px;
  border-radius: 8px;
  margin-bottom: 30px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.el-form{
  margin-top: 20px;
}
.strategy-form h3 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #dee2e6;
  padding-bottom: 10px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #495057;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  box-sizing: border-box;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-group input:focus {
  border-color: #007bff;
  outline: 0;
  box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
}

.form-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

button[type="submit"] {
  background-color: #007bff;
  color: white;
  padding: 12px 30px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: background-color 0.3s;
}

button[type="submit"]:hover:not(:disabled) {
  background-color: #0056b3;
}

button[type="submit"]:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.strategy-result {
  background-color: #e8f5e9;
  padding: 25px;
  border-radius: 8px;
  border-left: 5px solid #28a745;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.strategy-result h3 {
  margin-top: 0;
  color: #155724;
}

.result-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.result-item {
  display: flex;
  flex-direction: column;
}

.result-label {
  font-weight: bold;
  margin-bottom: 5px;
  color: #495057;
}

.result-value {
  font-size: 18px;
  font-weight: 500;
}

.action-buy {
  color: #28a745;
}

.action-sell {
  color: #dc3545;
}

.action-hold {
  color: #ffc107;
}

.result-details {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  margin-top: 20px;
}

.result-details h4 {
  margin-top: 0;
  color: #495057;
}

.result-details pre {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  overflow-x: auto;
  white-space: pre-wrap;
  font-size: 12px;
  line-height: 1.5;
  max-height: 300px;
  overflow-y: auto;
}

@media (min-width: 1024px) {
  .strategy-tabs {
    flex-wrap: nowrap;
  }
  
  .strategy-tabs button {
    padding: 12px 30px;
  }
  
  .form-row {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  }
  
  .result-summary {
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  }
}
</style>